import java.util.Collections;
import java.util.List;

public class FindLongestWord {

    public String findLongestWord(String s, List<String> dictionary) {
        Collections.sort(dictionary, (a, b) -> {
            if (a.length() == b.length()) return a.compareTo(b);
            return b.length() - a.length();
        });
        int n = s.length();
        for (int i = 0; i < dictionary.size(); i++) {
            String temp = dictionary.get(i);
            if (n < temp.length()) continue;
            if (process(s, temp)) return temp;
        }
        return "";
    }

    public boolean process(String s, String temp) {
        int p1 = 0;
        int p2 = 0;
        while (p1 < s.length() && p2 < temp.length()) {
            if (s.charAt(p1) == temp.charAt(p2)) ++p2;
            ++p1;
        }
        if (p2 == temp.length()) return true;
        return false;
    }
}
